JavaScript Enlightenment by Cody Lindley

JavaScript Enlightenment by Cody Lindley

Author:Cody Lindley [Cody Lindley]
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Programming Languages / JavaScript
ISBN: 9781449342876
Publisher: O'Reilly Media
Published: 2012-12-18T16:00:00+00:00


Using the this Keyword Inside a User-Defined Constructor Function

When a function is invoked with the new keyword, the value of this—as it’s stated in the constructor—refers to the instance itself. Said another way: in the constructor function, we can leverage the object via this before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().

Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

Live Code

<!DOCTYPE html><html lang="en"><body><script> var Person = function(name) { this.name = name || 'john doe'; // this will refer to the instance created } var cody = new Person('Cody Lindley'); /* create an instance, based on Person constructor */ console.log(cody.name); // logs 'Cody Lindley' </script></body></html>

Again, this refers to the “object that is to be” when the constructor function is invoked using the new keyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked—in this case the head object. Let’s examine this scenario.

Live Code

<!DOCTYPE html><html lang="en"><body><script> var Person = function(name) { this.name = name || 'john doe'; } var cody = Person('Cody Lindley'); // notice we did not use 'new' console.log(cody.name); // undefined, the value is actually set at window.name console.log(window.name); // logs 'Cody Lindley' </script></body></html>



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.